package com.qf.jwt.controller;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class AuthorController {

    private String secret = "asdaskufgdahjfdskfshdiugwerhoigerohpeugisdbcsdhjvduf";

    @PostMapping("/login")
    public String login(String username,String password){
        //1. 执行登录
        if("admin".equals(username) && "admin".equals(password)) {
            //2. 封装令牌
            String compact = Jwts.builder()
                    .setSubject("超级管理员")
                    .setIssuedAt(new Date())    // 设置有效期
                    .setExpiration(new Date(new Date().getTime() + 600000))  // 设置失效时间
                    .claim("role", "超级管理员,运营,市场")            // 随意设置,载荷中的信息
                    .claim("perm", "user:add,user:delete,user:select")  // 随意设置,载荷中的信息
                    .claim("ip","127.0.0.1")
                    .signWith(SignatureAlgorithm.HS256, secret.getBytes()) // 设置签名和secret
                    .compact();
            //3. 响应
            return compact;
        }
        //4. 登录失败
        return "Login Fail!!";
    }


    @PostMapping("/jiaoyan")
    public String jiaoYan(@RequestHeader(value = "token")String token){
        //1. 解密
        Claims claims = Jwts.parser().setSigningKey(secret.getBytes()).parseClaimsJws(token).getBody();

        //2. 获取信息
        String perm = (String) claims.get("perm");

        //3. 返回信息
        return perm;
    }

    //eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiLotoXnuqfnrqHnkIblkZgiLCJpYXQiOjE2MTI1MTQxNTAsImV4cCI6MTYxMjUxNDc1MCwicm9sZSI6Iui2hee6p-euoeeQhuWRmCzov5DokKUs5biC5Zy6IiwicGVybSI6InVzZXI6YWRkLHVzZXI6ZGVsZXRlLHVzZXI6c2VsZWN0In0.bWVV9D2E3_5NwwhzMTmR0oVCF6JU-zAdx2Ytmx3ayF0
    //eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiLotoXnuqfnrqHnkIblkZgiLCJpYXQiOjE2MTI1MTQ0NzIsImV4cCI6MTYxMjUxNTA3Miwicm9sZSI6Iui2hee6p-euoeeQhuWRmCzov5DokKUs5biC5Zy6IiwicGVybSI6InVzZXI6YWRkLHVzZXI6ZGVsZXRlLHVzZXI6c2VsZWN0In0.qr-7k2vxnNP_mhVjRXNbAGLWwEsJbHCvid9vMdF6WOw
}
